package au.com.mason.propertyTracker.controller;

import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import au.com.mason.propertyTracker.form.AutoAddPropertyForm;
import au.com.mason.propertyTracker.service.PropertyService;

@Controller
public class AutoAddProperty {
	
	private PropertyService propertyService;
	
	@Autowired
	public AutoAddProperty(PropertyService propertyService) {
		this.propertyService = propertyService;
	}
	
	@RequestMapping("/DisplayAutoAddProperty.action")
	public String displayAddProperty(Map model) {
		AutoAddPropertyForm autoAddPropertyForm = new AutoAddPropertyForm();
		
		model.put("autoAddPropertyForm", autoAddPropertyForm);
		
		return "autoAddProperty";
	}
	
	@RequestMapping("/AutoAddProperty.action")
	public String addProperty(HttpSession session, AutoAddPropertyForm autoAddPropertyForm) {
		ArrayList<String> messages = new ArrayList<String>();
		for (String url : autoAddPropertyForm.getUrls()) {
			if (url != null && !url.equals("")) {
				if (!propertyService.addProperty(url, autoAddPropertyForm.isRental())) {
					messages.add("Property with url " + url + " is already added.");
				}
			}
		}
		
		session.setAttribute("messages", messages);
		
		return "redirect:SubmitFilterPropertiesFromSession.action";
	}

}
